import { defineStore } from 'pinia'
import { ref } from 'vue'
import { postRefreshToken } from '@/api/User'
import type { UserProfile } from '@/types/index'

export const useMemberStore = defineStore(
  'member',
  () => {
    const profileSummary = ref<UserProfile>(null)
    const isRefreshing = ref(false)
    const setProfileSummary = (val: any) => {
      profileSummary.value = val
    }

    const clearProfileSummary = () => {
      profileSummary.value = null
      uni.removeStorageSync('refreshToken')
      uni.removeStorageSync('accessToken')
    }

    /**
   * 刷新Token
   * 使用单例模式确保同一时间只有一个刷新请求
   * 返回Promise，成功时返回新的token信息，失败时返回错误
   */
  const refreshTokenPromise = ref<Promise<any> | null>(null)
  
  const refreshToken = async () => {
    // 如果已经有刷新请求在进行中，直接返回该Promise
    if (refreshTokenPromise.value) {
      return refreshTokenPromise.value
    }

    const currentRefreshToken = uni.getStorageSync('refreshToken')
    if (!currentRefreshToken) {
      return Promise.reject('没有可用的刷新令牌')
    }

    isRefreshing.value = true
    
    // 创建新的刷新请求Promise，使用async/await和try/catch结构
    console.log('开始创建刷新Token Promise')
    
    // 创建一个新的Promise来包装整个过程
    refreshTokenPromise.value = new Promise(async (resolve, reject) => {
      try {
        console.log('开始调用postRefreshToken')
        const res = await postRefreshToken({ refreshToken: currentRefreshToken })
        console.log('刷新Token API返回结果:', res)
        
        if (res?.data?.refreshToken && res?.data?.accessToken) {
          // 保存新的token
          uni.setStorageSync('refreshToken', res.data.refreshToken)
          uni.setStorageSync('accessToken', res.data.accessToken)
          resolve(res.data)
        } else {
          console.error('刷新Token返回数据格式错误:', res)
          reject(new Error('刷新Token失败：返回格式错误'))
        }
      } catch (err) {
        // 增强错误日志
        console.log('member.ts refreshToken try/catch error:', err)
        if (err instanceof Error) {
          console.log('Error name:', err.name)
          console.log('Error message:', err.message)
          console.log('Error stack:', err.stack)
        } else {
          console.log('Non-Error object received:', typeof err, err)
        }
        
        // 清除用户信息和token
        clearProfileSummary()
        
        // 拒绝Promise
        reject(err || new Error('刷新Token请求失败'))
      } finally {
        // 重置状态
        isRefreshing.value = false
        // 清除Promise引用，允许下次刷新
        setTimeout(() => {
          refreshTokenPromise.value = null
        }, 0)
      }
    })

    return refreshTokenPromise.value
    }

    return {
      profileSummary,
      setProfileSummary,
      clearProfileSummary,
      refreshToken,
      isRefreshing
    }
  },
  {
    // 小程序端配置
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
      },
    },
  },
)
    